<script setup>
import { Edit, Delete, Refresh } from "@element-plus/icons-vue";
import { Search, Plus } from "@element-plus/icons-vue";
import { ref, reactive, onMounted } from "vue";
import {
  getAdminPolicyList,
  getPolicyDetail,
  addPolicy,
  updatePolicy,
  deletePolicy,
} from "@/api/policy";
import { formatTime } from "@/utils/format";

const pform = ref(null);

// 请求参数
const searchForm = reactive({
  current: 1,
  size: 10,
  keyword: "",
});

// 存储政策数据列表
const policyList = ref([]);
// 存储政策数据总数
const total = ref(0);
// 加载状态
const loading = ref(false);

// 当前操作类型（add/edit/view）
const currentMode = ref("add");
// 当前选中的政策
const currentPolicy = ref({});

// 获取政策列表
const getPolicies = async () => {
  loading.value = true;
  const response = await getAdminPolicyList(searchForm);
  policyList.value = response.data.data.data || [];
  total.value = response.data.data.total || 0;
  loading.value = false;
};

// 搜索政策
const handleSearch = () => {
  searchForm.current = 1;
  getPolicies();
};

// 重置搜索
const handleReset = () => {
  searchForm.keyword = "";
  searchForm.current = 1;
  getPolicies();
};

// 分页变更
const handleSizeChange = (val) => {
  searchForm.size = val;
  getPolicies();
};
const handleCurrentChange = (val) => {
  searchForm.current = val;
  getPolicies();
};

// 添加政策
const handleAdd = () => {
  pform.value.handleOpen({}, "add");
};

// 编辑政策
const handleEdit = async (row) => {
  pform.value.handleOpen(row, "edit");
};

// 查看政策
const handleView = async (row) => {
  pform.value.handleOpen(row, "view");
};

// 删除政策
const handleDelete = async (row) => {
  await ElMessageBox.confirm("确定要删除该政策吗？", "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });

  await deletePolicy(row.policyId);
  ElMessage.success("删除成功");
  getPolicies();
};

// 保存政策
const handleSave = async (e) => {
  if (e == "add") {
    // 跳转到最后一页，如果最后一页满了，则跳转到最后一页+1
    searchForm.current = Math.ceil(total.value / searchForm.size);
    if (total.value % searchForm.size === 0) {
      searchForm.current = Math.ceil(total.value / searchForm.size) + 1;
    }
  }
  getPolicies();
};

onMounted(() => {
  getPolicies();
});

// 查看详情
const handleRowClick = (row) => {
  handleView(row);
};
</script>

<template>
  <Card title="政策管理">
    <!-- 具名插槽--按钮 -->
    <template #extra>
      <el-button type="primary" @click="handleAdd" :icon="Plus">
        新增政策
      </el-button>
    </template>

    <el-form inline style="margin-left: 20px">
      <el-form-item>
        <el-input
          :prefix-icon="Search"
          v-model="searchForm.keyword"
          placeholder="请输入政策标题"
          style="width: 200px; margin-right: 10px"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">搜索 </el-button>
        <el-button :icon="Refresh" @click="handleReset">重置 </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="policyList"
      style="width: 100%"
      @row-click="handleRowClick"
      row-class-name="clickable-row"
    >
      <el-table-column type="index" label="序列" width="100" />
      <el-table-column
        prop="title"
        label="政策标题"
        min-width="200"
        align="center"
      >
        <template #default="scope">
          <div class="title-text" :title="scope.row.title">
            {{ scope.row.title }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="policyType"
        label="政策类型"
        width="180"
        align="center"
      />
      <el-table-column
        prop="publishTime"
        label="创建时间"
        width="180"
        align="center"
      >
        <template #default="{ row }">
          {{ formatTime(row.publishTime) }}
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.status === 0" type="danger">禁用</el-tag>
          <el-tag v-else-if="row.status === 1" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" align="center">
        <template #default="scope">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click.stop="handleEdit(scope.row)"
            style="margin-right: 8px"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click.stop="handleDelete(scope.row)"
          ></el-button>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <el-pagination
      v-model:current-page="searchForm.current"
      v-model:page-size="searchForm.size"
      :page-sizes="[5, 10, 20, 50]"
      background
      layout="jumper,total, sizes, prev, pager, next"
      :total="Number(total)"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 50px; justify-content: flex-end"
    />
  </Card>

  <!-- 政策表单抽屉组件 -->
  <PolicyForm ref="pform" @save="handleSave" />
</template>

<style lang="scss" scoped>
.policy-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.title-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-normal {
  color: #409eff;
}

.status-disabled {
  color: #909399;
}

::v-deep .clickable-row {
  cursor: pointer;
}

::v-deep .clickable-row:hover {
  background-color: #f5f7fa;
}
</style>
